﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Net;
using System.IO;
using Tsingda.XXB.Common;

namespace Tsingda.XXB.Web.Controllers
{
    using System.Data.SqlClient;
    using TestClient.Models;
    public class TestController : Controller
    {
        static readonly string conn;// = System.Configuration.ConfigurationManager.ConnectionStrings["DB"] == null ? string.Empty : System.Configuration.ConfigurationManager.ConnectionStrings["DB"].ToString();

        static string serverIP;

        static TestController()
        {
            serverIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            conn = string.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;
                                 User Instance=False;User ID={2};Password={3};MultipleActiveResultSets=true"
                , ConfigCache.ConfigFactory.Instance.GetConfig<Config>().DBIP
                , ConfigCache.ConfigFactory.Instance.GetConfig<Config>().DBName
                , ConfigCache.ConfigFactory.Instance.GetConfig<Config>().DBUser
                , ConfigCache.ConfigFactory.Instance.GetConfig<Config>().DBPassword);

        }

        #region 测试服务器
        public ContentResult TestIIS()
        {
            this.ControllerContext.HttpContext.Response.AddHeader("cache-control", "no-cache");
            string callback = Request["jsonpcallback"];
            string msg = "{ServerName:'" + ConfigCache.ConfigFactory.Instance.GetConfig<Config>().ServerName + "',DBIP:'" + ConfigCache.ConfigFactory.Instance.GetConfig<Config>().DBIP + "', IISMessage : 'OK',DBMessage : '" + TestDB() + "', Server: '" + serverIP + "' }";
            return Content(callback + "(" + msg + ")");　//反回一个callback(msg)对象
        }

        string TestDB()
        {
            string message = "false";
            try
            {
                if (string.IsNullOrEmpty(conn))
                    throw new Exception("请设置config.config里的数据连接字符串DB");

                using (SqlConnection _conn = new SqlConnection(conn))
                {
                    using (SqlCommand comm = new SqlCommand("SELECT COUNT(1)  FROM sys.tables", _conn))
                    {
                        try
                        {
                            comm.ExecuteReader();
                        }
                        catch (Exception)
                        {
                            message = "Fail";
                        }

                    }
                }
                message = "OK";
            }
            catch (Exception)
            {
                message = "Fail";
            }
            return message;
        }
        #endregion



        #region 工具类
        /// <summary>
        /// 匿名方法的使用
        /// </summary>
        /// <param name="url"></param>
        public static void TestRequest(string url)
        {
            WebRequest request = HttpWebRequest.Create(url);
            request.BeginGetResponse(delegate(IAsyncResult ar)
            {
                using (WebResponse response = request.EndGetResponse(ar))
                {
                    Console.WriteLine("{0}: {1}", url, response.ContentLength);
                }
            },
            null);
        }

        /// <summary>
        /// 执行代码规范
        /// </summary>
        public interface IAction
        {
            void Action();
        }

        /// <summary>
        /// 老赵的性能测试工具
        /// </summary>
        public static class CodeTimer
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            static extern bool GetThreadTimes(IntPtr hThread, out long lpCreationTime, out long lpExitTime, out long lpKernelTime, out long lpUserTime);

            [DllImport("kernel32.dll")]
            static extern IntPtr GetCurrentThread();
            public delegate void ActionDelegate();
            private static long GetCurrentThreadTimes()
            {
                long l;
                long kernelTime, userTimer;
                GetThreadTimes(GetCurrentThread(), out l, out l, out kernelTime, out userTimer);
                return kernelTime + userTimer;
            }
            static CodeTimer()
            {
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            public static void Time(string name, int iteration, ActionDelegate action)
            {
                if (String.IsNullOrEmpty(name))
                {
                    return;
                }
                if (action == null)
                {
                    return;
                }

                //1. Print name
                ConsoleColor currentForeColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(name);

                // 2. Record the latest GC counts
                //GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                GC.Collect(GC.MaxGeneration);
                int[] gcCounts = new int[GC.MaxGeneration + 1];
                for (int i = 0; i <= GC.MaxGeneration; i++)
                {
                    gcCounts[i] = GC.CollectionCount(i);
                }

                // 3. Run action
                Stopwatch watch = new Stopwatch();
                watch.Start();
                long ticksFst = GetCurrentThreadTimes(); //100 nanosecond one tick
                for (int i = 0; i < iteration; i++) action();
                long ticks = GetCurrentThreadTimes() - ticksFst;
                watch.Stop();

                // 4. Print CPU
                Console.ForegroundColor = currentForeColor;
                Console.WriteLine("\tTime Elapsed:\t\t" +
                   watch.ElapsedMilliseconds.ToString("N0") + "ms");
                Console.WriteLine("\tTime Elapsed (one time):" +
                   (watch.ElapsedMilliseconds / iteration).ToString("N0") + "ms");
                Console.WriteLine("\tCPU time:\t\t" + (ticks * 100).ToString("N0")
                   + "ns");
                Console.WriteLine("\tCPU time (one time):\t" + (ticks * 100 /
                   iteration).ToString("N0") + "ns");

                // 5. Print GC
                for (int i = 0; i <= GC.MaxGeneration; i++)
                {
                    int count = GC.CollectionCount(i) - gcCounts[i];
                    Console.WriteLine("\tGen " + i + ": \t\t\t" + count);
                }
                Console.WriteLine();
            }



            public static void Time(string name, int iteration, IAction action)
            {
                if (String.IsNullOrEmpty(name))
                {
                    return;
                }

                if (action == null)
                {
                    return;
                }

                //1. Print name
                ConsoleColor currentForeColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(name);

                // 2. Record the latest GC counts
                //GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                GC.Collect(GC.MaxGeneration);
                int[] gcCounts = new int[GC.MaxGeneration + 1];
                for (int i = 0; i <= GC.MaxGeneration; i++)
                {
                    gcCounts[i] = GC.CollectionCount(i);
                }

                // 3. Run action
                Stopwatch watch = new Stopwatch();
                watch.Start();
                long ticksFst = GetCurrentThreadTimes(); //100 nanosecond one tick
                for (int i = 0; i < iteration; i++) action.Action();
                long ticks = GetCurrentThreadTimes() - ticksFst;
                watch.Stop();

                // 4. Print CPU
                Console.ForegroundColor = currentForeColor;
                Console.WriteLine("\tTime Elapsed:\t\t" +
                   watch.ElapsedMilliseconds.ToString("N0") + "ms");
                Console.WriteLine("\tTime Elapsed (one time):" +
                   (watch.ElapsedMilliseconds / iteration).ToString("N0") + "ms");
                Console.WriteLine("\tCPU time:\t\t" + (ticks * 100).ToString("N0")
                    + "ns");
                Console.WriteLine("\tCPU time (one time):\t" + (ticks * 100 /
                    iteration).ToString("N0") + "ns");

                // 5. Print GC
                for (int i = 0; i <= GC.MaxGeneration; i++)
                {
                    int count = GC.CollectionCount(i) - gcCounts[i];
                    Console.WriteLine("\tGen " + i + ": \t\t\t" + count);
                }
                Console.WriteLine();
            }
        }
        #endregion




    }
}
